const dbPool = require("../database");

// 添加订单路由回调
exports.addOrder = function (req, res) {
  const goodsList = req.body.goodsList;

  // 获取要购买商品的数据
  let sqlStr = "select * from goods where id in (";
  sqlStr = goodsList.reduce((acc, curr, idx, arr) => {
    if (idx !== arr.length - 1) {
      return acc + `${curr.goods_id},`;
    }
    return acc + `${curr.goods_id})`;
  }, sqlStr);
  dbPool.query(sqlStr, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== goodsList.length) return res.cc("添加订单失败！");
    const goodsData = results;
    // 根据商品信息获取和请求数据计算价格 total
    let total = 0;
    for (let i = 0; i < goodsList.length; i++) {
      for (let j = 0; j < goodsData.length; j++) {
        if (goodsData[j].id === goodsList[i].goods_id) {
          total += (goodsData[j].price * parseInt(goodsList[i].amount));
          goodsData[j].amount = goodsList[i].amount;
          if (goodsList[i].amount > goodsData[j].stock) return res.cc(`${goodsData[j].name},库存不足！`);
        }
      }
    }

    // 获取收货地址
    const sqlStr = "select name, phone, address from user where id = ?";
    dbPool.query(sqlStr, req.user.id, (err, results) => {
      if (err) return res.cc(err);

      // 添加订单
      const sqlStr = "insert into `order` set ?";
      dbPool.query(sqlStr, { time: Date.now(), total, pay_type: req.body.pay_type, ...results[0], user_id: req.user.id }, (err, results) => {
        if (err) return res.cc(err);
        if (results.affectedRows !== 1) return res.cc("添加订单失败！");
        const order_id = results.insertId;

        // 添加订单商品
        let sqlStr = "insert into order_item (price, amount, goods_id, order_id) values ";
        sqlStr = goodsData.reduce((acc, curr, idx, arr) => {
          if (idx !== arr.length - 1) {
            return acc += `(${curr.price}, ${curr.amount}, ${curr.id}, ${order_id}), `;
          }
          return acc += `(${curr.price}, ${curr.amount}, ${curr.id}, ${order_id})`;
        }, sqlStr);
        dbPool.query(sqlStr, (err, results) => {
          if (err) return res.cc(err);
          if (results.affectedRows !== goodsData.length) return res.cc("添加订单失败！");
          let sqlStr = "delete from shopping_cart where goods_id in (";
          sqlStr = goodsData.reduce((acc, curr, idx, arr) => {
            if (idx !== arr.length - 1) {
              return acc + `${curr.id}, `;
            }
            return acc + `${curr.id}) and user_id = ${req.user.id}`;
          }, sqlStr);
          dbPool.query(sqlStr, (err, results) => {
            if (err) res.cc(err);
            if (results.affectedRows !== goodsList.length) return res.cc("添加订单失败！");

            // 修改数量 和 销量
            for (let i = 0; i < goodsData.length; i++) {
              for (let j = 0; j < goodsList.length; j++) {
                if (goodsData[i].id === goodsList[j].goods_id) {
                  const stock = goodsData[i].stock - goodsList[j].amount;
                  const sales = goodsData[i].sales + goodsList[j].amount;
                  const id = goodsData[i].id;
                  const sqlStr = "update goods set stock = ?, sales = ? where id = ?";
                  dbPool.query(sqlStr, [stock, sales, id], (err, results) => {
                    if (err) return res.cc(err);
                    if (results.affectedRows !== 1) return res.cc("出错了！");
                  })
                }
              }
            }
            res.cc("添加订单成功！", 1);
          })
        })
      })
    });
  })
}

// 获取订单数据路由回调
exports.getOrder = function (req, res) {
  const sqlStr = "select * from `order` where user_id = ?  order by id desc";
  dbPool.query(sqlStr, req.user.id, (err, results) => {
    if (err) return res.cc(err);
    let orderData = results;
    let sqlStr = "select gs.name, oi.* from order_item oi join goods gs on oi.goods_id = gs.id  where order_id in (";
    sqlStr = orderData.reduce((acc, curr, idx, arr) => {
      if (idx !== arr.length - 1) {
        return acc + `${curr.id}, `;
      }
      return acc + `${curr.id})`
    }, sqlStr)
    dbPool.query(sqlStr, (err, results) => {
      if (err) return res.cc(err);
      orderData.map((item) => {
        item.goodsList = [];
        for (let i = 0; i < results.length; i++) {
          if (item.id === results[i].order_id) {
            item.goodsList.push(results[i]);
          }
        }
        return item.goodsList;
      })
      res.send({
        status: 1,
        message: "获取订单数据成功！",
        data: orderData,
      });
    })
  })
}

// 修改订单状态路由回调
exports.upState = function (req, res) {
  const sqlStr = "update `order` set `state` = ? WHERE `id` = ?";
  dbPool.query(sqlStr, [req.body.state, req.body.id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("修改订单状态失败！");
    res.cc("修改订单状态成功！", 1);
  })
}